<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <a-row >
          <div :class="advanced ? null: 'fold'">
            <a-col :md="12" :sm="24" >
              <a-form-item
                label="类别名称"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 18, offset: 2}">
                <a-input v-model="queryParams.name"/>
              </a-form-item>
            </a-col>
          </div>
          <span style="float: right; margin-top: 3px;">
            <a-button type="primary" @click="search">查询</a-button>
            <a-button style="margin-left: 8px" @click="reset">重置</a-button>
          </span>
        </a-row>
      </a-form>
    </div>
    <div>
      <div class="operator">
        <a-button type="primary" ghost @click="add" v-hasPermission="'category:add'">新增</a-button>
        <a-button @click="batchDelete" v-hasPermission="'category:delete'">删除</a-button>
      </div>
      <!-- 表格区域 -->
      <a-table ref="TableInfo"
               :columns="columns"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               :rowKey="record => record.id"
               :scroll="{ x: 900 }"
               @change="handleTableChange">
        <template slot="operation" slot-scope="text, record">
          <a-icon v-hasPermission="'category:update'" type="setting" theme="twoTone" twoToneColor="#4a9ff5" @click="edit(record)" title="修改类别"></a-icon>
          &nbsp;
          <a-badge v-hasNoPermission="'category:update'" status="warning" text="无权限"></a-badge>
        </template>
      </a-table>
    </div>
    <!-- 新增类别 -->
    <category-add
      @close="handleCategoryAddClose"
      @success="handleCategoryAddSuccess"
      :categoryAddVisiable="categoryAddVisiable">
    </category-add>
    <!-- 修改类别 -->
    <category-edit
      ref="categoryEdit"
      @close="handleCategoryEditClose"
      @success="handleCategoryEditSuccess"
      :categoryEditVisiable="categoryEditVisiable">
    </category-edit>
  </a-card>
</template>

<script>
import CategoryAdd from './CategoryAdd'
import CategoryEdit from './CategoryEdit'
import defaultPagination from '../../../utils/common'

export default {
  name: 'Category',
  components: { CategoryAdd, CategoryEdit },
  data () {
    return {
      advanced: false,
      categoryAddVisiable: false,
      categoryEditVisiable: false,
      queryParams: {},
      filteredInfo: null,
      selectedRowKeys: [],
      sortedInfo: null,
      paginationInfo: null,
      dataSource: [],
      loading: false,
      pagination: defaultPagination
    }
  },
  computed: {
    columns () {
      // eslint-disable-next-line no-unused-vars
      let { sortedInfo, filteredInfo } = this
      sortedInfo = sortedInfo || {}
      filteredInfo = filteredInfo || {}
      return [{
        title: '类别名称',
        dataIndex: 'name',
        key: 'name'
      }, {
        title: '优先级',
        dataIndex: 'priority',
        key: 'priority'
      }, {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        customRender: (text, row, index) => {
          switch (text) {
            case 'ENABLE':
              return <a-tag color="cyan">开启</a-tag>
            case 'DISABLE':
              return <a-tag color="red">关闭</a-tag>
            default:
              return <a-tag color="yellow">未知</a-tag>
          }
        },
        filters: [
          { text: '开启', value: 'ENABLE' },
          { text: '关闭', value: 'DISABLE' }
        ],
        filterMultiple: false,
        filteredValue: filteredInfo.status || null,
        onFilter: (value, record) => record.status.includes(value)
      }, {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime'
      }, {
        title: '操作',
        dataIndex: 'operation',
        scopedSlots: { customRender: 'operation' }
      }]
    }
  },
  mounted () {
    this.fetch()
  },
  methods: {
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    add () {
      this.categoryAddVisiable = true
    },
    handleCategoryAddClose () {
      this.categoryAddVisiable = false
    },
    handleCategoryAddSuccess () {
      this.categoryAddVisiable = false
      this.$message.success('新增类别成功')
      this.search()
    },
    edit (record) {
      this.$refs.categoryEdit.setFormValues(record)
      this.categoryEditVisiable = true
    },
    handleCategoryEditClose () {
      this.categoryEditVisiable = false
    },
    handleCategoryEditSuccess () {
      this.categoryEditVisiable = false
      this.$message.success('修改类别成功')
      this.search()
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定删除所选中的记录?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk () {
          let categoryIds = that.selectedRowKeys.join(',')
          that.$delete('category/' + categoryIds).then(() => {
            that.$message.success('删除成功')
            that.selectedRowKeys = []
            that.search()
          }).catch(() => {
            this.loading = false
            that.$message.error('删除失败')
          })
        },
        onCancel () {
          that.selectedRowKeys = []
        }
      })
    },
    search () {
      let {sortedInfo} = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.restPagination()
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams
      })
    },
    reset () {
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      this.restPagination()
      // 重置列过滤器规则
      this.filteredInfo = null
      // 重置列排序规则
      this.sortedInfo = null
      // 重置查询参数
      this.queryParams = {}
      this.fetch()
    },
    restPagination () {
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
    },
    handleTableChange (pagination, filters, sorter) {
      // 将这三个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination
      this.filteredInfo = filters
      this.sortedInfo = sorter

      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.queryParams,
        ...filters
      })
    },
    fetch (params = {}) {
      // 显示loading
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      this.$get('category', {
        ...params
      }).then((r) => {
        let data = r.data
        const pagination = { ...this.pagination }
        pagination.total = data.total
        this.dataSource = data.rows
        this.pagination = pagination
        // 数据加载完毕，关闭loading
        this.loading = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
  @import "../../../../static/less/Common";
</style>
